<template>
        <view :class="[{'class-manger-content':isChoose}]">
			<u-navbar class="navbar" :border-bottom="false" title="分类" :title-size="36" :title-bold="true" :title-color="textColor" :background="{backgroundColor: bgColor}" >
			</u-navbar>
			<view class="u-p-35">
				<view class="user-box ">
				<m-tree
				v-if="isShowTree"
				    class=""
				    ref="mtree"
				    :defaultProps="defaultProps"
				    :data="tree"
				    :divider="divider"
				    :edit="edit"
				    :unfold="true"
					:isChoose="isChoose"
				    @node-click="nodeClick" 
				    @up-item="upNode" 
				    @down-item="downNode" 
				    @add-item="addNode" 
				    @edit-item="editNode" 
				    @delete-item="deleteNode"
				    @finger-action="fingerAction"
				    @long-press="longpressNode"></m-tree>
				</view>
			</view>
			<view class="btn-bottom-group" v-if="isChoose">
				<u-button type="default" :custom-style="customStyle" :hover-class="'none'" @click="backSendFn">确定</u-button>
				<u-button  :custom-style="cancelStyle" :plain="false" :hover-class="'none'" @click="cancelSendFn" class="u-m-t-35" >取消</u-button>
			</view>
			<akLoading isFullScreen :active="loading"></akLoading>
        </view>
    </template>

    <script>
		import { useShopStore } from '@/store/shop.js';
		import { mapState } from 'pinia';
        export default {
            data() {
                return {
					loading:false,
					isShowTree:false,
					customStyle:{
						color:'#fff',
						background:'#ffbb1a',
						borderRadius:'100rpx',
						height:'88rpx',
						lineHeight:'88rpx',
						fontSize:'34rpx'
					},
					cancelStyle:{
						height:'88rpx',
						borderRadius:'100rpx',
						lineHeight:'88rpx',
						fontSize:'34rpx'
					},
                    defaultProps: {
                        id: 'id',             // 此项为id项的key
                        children: 'children', // 此项为修改子集数据的key
                        name: 'name' // 此项为修改显示数据的key
                    },
                    divider: false,
                    edit: true,
					isChoose:false,
                    tree: [],
					backSendData:{
						name:'',
						id:'',
					}
                }
            },
			onLoad(options) {
				this.controllerType = options.type;
				if(options.isChoose == 'true'){
					this.edit = false;
					this.isChoose = true;
					// this.controllerType = 'Seller';
					// this.$store.commit('shop/SET_CHOOSEITEM_ID',options.id);
					this.backSendData.name = options.name;
					this.backSendData.id = options.id;
				}else{
					this.edit = true;
					this.isChoose = false;
				}
				this.getTreeListFn()
			},
			computed:{
				...mapState(useShopStore, {storeShop: 'shop'})
			},
            methods: {
				backSendFn(){
					 let pages = getCurrentPages(); // 当前页面
					let beforePage = pages[pages.length - 2]; // 上一页
					uni.$emit('sendPlateClass', this.backSendData)
					uni.navigateBack({
						delta: 1
					})
				},
				cancelSendFn(){
					 let pages = getCurrentPages(); // 当前页面
					let beforePage = pages[pages.length - 2]; // 上一页
					console.log(beforePage);
					this.backSendData.name = '';
					this.backSendData.id = '';
					uni.$emit('sendPlateClass', this.backSendData)
					uni.navigateBack({
						delta: 1
					})
				},
                //遍历id节点并删除
                removeNodeData(datas, id){ //遍历树  获取id数组
                  for(var i in datas){
                    if(id===datas[i].id) {
                        // datas.push(datas[i]);
                        datas.splice(i,1);
                        break;
                    } else {
                        if(datas[i].children){  //存在子节点就递归
                          this.removeNodeData(datas[i].children, id);
                        }
                    }
                  }
                },
                //遍历id节点添加子项
                addNodeData(datas, id, nodedata){ //遍历树  获取id数组
                    var addflag = false;
                    if(id===0) {
                        datas.unshift(nodedata);
                        addflag=true;
                    } else {
                        for(var i in datas){
                            if(id===datas[i].id) {
                                // datas.push(datas[i]);
                                datas[i].children.unshift(nodedata);
                                addflag=true;
                                break;
                            } else {
                                if(datas[i].children){  //存在子节点就递归
                                  this.addNodeData(datas[i].children, id, nodedata);
                                }
                            }
                        }
                    }
                    return addflag;
                },
                //节点点击事件
                nodeClick(e) {
					if(this.isChoose){
						// this.$store.commit('shop/SET_CHOOSEITEM_ID',e.id);
						this.backSendData.name = e.name;
						this.backSendData.id = e.id;
					}
                },
                //节点up按钮点击事件
                upNode(e) {
                    const that = this;
                    console.log('upNode');
                    if(e.index!=0){
                        // 根据自身需求，自行修改数据处理方法；

                        // up上移操作，排序并更新tree中对应元素sort属性
                        var data = {
                            pnode: {}, 
                            itemA: {id: e.items[e.index-1].id, sort: e.items[e.index].sort}, 
                            itemB: {id: e.items[e.index].id, sort: e.items[e.index-1].sort},
                        }
                        that.$refs.mtree.treeSort(that.tree, e.item.pid, data); // 调用组件方法 排序sort 从小到大排序
                        
                    }
                },
                //节点down按钮点击事件
                downNode(e) { 
                    const that = this;
                    console.log('downNode');
                    if(e.index != e.items.length-1){
                        // 根据自身需求，自行修改数据处理方法；

                        // down下移操作，排序并更新tree中对应元素sort属性
                        var data = {
                            pnode: {}, 
                            itemA: {id: e.items[e.index+1].id, sort: e.items[e.index].sort}, 
                            itemB: {id: e.items[e.index].id, sort: e.items[e.index+1].sort},
                        }
                        that.$refs.mtree.treeSort(that.tree, e.item.pid, data); // 调用组件方法 排序sort 从小到大排序
                    }
                },
                //节点新增按钮点击事件
                async addNode(e) {
                    //e.pNodeData, e.addContent
                    // 根据自身需求，自行修改数据新增方法；
                    // 可以配合异步请求 执行服务器删除操作
					
                    let data={};
					let params={};
                    if(e.pNodeData.id===0) {
                        // data={id: this.tree.length + 1, pid: e.id, label:'新增节点', name:'新增节点',children:[]}
                        data={id: this.tree.length + 1, pid: e.id,  name:'新增节点',children:[],parentId:null}
						params = {
							shopId:this.storeShop.id,
							name:e.addContent
						}
                    } else {
                        // data={id: e.pNodeData.id + e.pNodeData.children.length + 100, pid: e.pNodeData.id, label: e.addContent, name: e.addContent,children:[]}
                        data={id: e.pNodeData.id , pid: e.pNodeData.id,  name: e.addContent,children:[],parentId:e.pNodeData.id}
						params = {
							shopId:this.storeShop.id,
							name:e.addContent,
							parentId:e.pNodeData.id
						}
                    }
					// console.log(params);
                    if(data) {
						this.loading = true;
						const res = await  this.$newHttp.put('api/v1.2/Product/SaveCategory',params);
						this.loading = false;
						if(res.code === 200){
							this.getTreeListFn();
							// this.addNodeData(this.tree, e.pNodeData.id, data);
						}else{
							this.$u.toast('新增分类失败，错误信息：'+res.erroMessage)
						}
                    }
                },
                //节点更新按钮点击事件
                async editNode(e) {
                    //e.pNodeData, e.editContent
                    if(e.editContent.length >= 2 && e.editContent.length <= 16) {
                        // e.pNodeData.label = e.editContent;
                        // e.pNodeData.name = e.editContent;
						let params = {
							shopId:this.storeShop.id,
							name:e.editContent,
							id:e.pNodeData.id
						};
						if(e.parentId){
							params.parentId = e.parentId;
						}
						this.loading = true;
						const res = await  this.$newHttp.put('api/v1.2/Product/SaveCategory',params);
						this.loading = false;
						if(res.code === 200){
							this.getTreeListFn();
							// this.addNodeData(this.tree, e.pNodeData.id, data);
						}else{
							this.$u.toast('修改分类信息失败，错误信息：'+res.erroMessage)
						}
                    }
                    // 节点已更新
                    
                    /* const that = this;
                    var updateData = {
                        data: {id: e.pNodeData.id, name: e.editContent},
                        params: {id: e.pNodeData.id}
                    }; 
                    new AreaService().update(updateData).then(result => {
                        if(result.code === 0) {
                            if(result.data.id) {
                                that.getList();
                            } else {
                                that.getList();
                            }
                            CommonUtil.toast(`更新巡更区域成功`, 2000);
                        } else {
                            CommonUtil.toast(`更新失败:` + result.message, 2000);
                        }
                    })
                    CommonUtil.toast(e.editContent + `更新成功`, 2000); */
                },
                //节点删除按钮点击事件
               async deleteNode(e) {
                    // 根据自身需求，自行修改数据删除方法；
                    // if(this.removeNodeData(this.tree, e.id)) {
                    //     // 可以配合异步请求 执行服务器删除操作
                    //     console.log('删除ID:', e,id, '数据');
                    // }
					let params = {
						shopId:this.storeShop.id,
						name:e.editContent,
						id:e.id
					}
					this.loading = true;
					const res = await this.$newHttp.delete('api/v1.2/Product/DeleteCategory',params);
					this.loading = false;
					if(res.code === 200){
						this.getTreeListFn();
						// this.addNodeData(this.tree, e.pNodeData.id, data);
					}else{
						this.$u.toast('删除失败，错误信息：'+res.erroMessage)
					}
                },
                //节点滑动
                fingerAction(e) {
                    // console.log('节点滑动fingerAction', JSON.stringify(e));
                },
                //节点选线长按事件
                longpressNode(e) {
                    // console.log('长按的项目longpress', JSON.stringify(e));
                },
				async getTreeListFn(){
					let params  = {
						ShopId:this.storeShop.id,
						IncludeChildren:true
					}
					// Seller  BrandOwner
					// const res = await this.$newHttp.get('api/BrandOwner/GetCategories',{params:params});
					this.loading = true;
					const res = await this.$newHttp.get('api/v1.2/ShanNiang/GetPlatformCategories',{params:params});
					this.loading = false;
					if(res.code === 200){
						this.isShowTree = true;
						this.tree = res.data;
					}else{
						this.$u.toast('获取分类列表失败，错误信息：'+res.erroMessage)
					}
				}
            }
        }
    </script>

    <style lang="scss">
		.class-manger-content{
			min-height: 100vh;
			box-sizing: border-box;
			padding-bottom: 400rpx;
			
			.btn-bottom-group{
				background-color: #f8f8f8;
				height: 400rpx;
				width: 100%;
				position: fixed;
				bottom: 0;
				left: 0;
				box-sizing: border-box;
				padding: 50rpx 35rpx;
				.u-hairline-border:after{
					// border: none;
					border-radius: 100rpx;
				}
			}
		}
    .user-box{
        // background-color: #fff;
    }
    </style>
